package com.yh.lq.robot;

import com.alibaba.fastjson.JSONObject;
import com.yh.lq.utils.AesUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

/**
 * 获取返回结果，需要增加同步阻塞
 */
@Slf4j
public class ApiBlockSender implements ApiSender {

    private final WebSocketSession apiSession;
    private JSONObject responseJSON;
    private final Long apiTimeout;
    private String robotSecretKey;

    public ApiBlockSender(WebSocketSession apiSession, Long apiTimeout,String robotSecretKey) {
        this.apiSession = apiSession;
        this.apiTimeout = apiTimeout;
        this.robotSecretKey = robotSecretKey;
    }

    @Override
    public  JSONObject sendApiJson(JSONObject apiJSON) throws Exception {
        synchronized (apiSession) {
            log.debug("send msg:{}",apiJSON);
            String sendMsg=apiJSON.toJSONString();
            if(!StringUtils.isEmpty(robotSecretKey)){
                sendMsg= AesUtil.aesEncrypt(sendMsg,robotSecretKey);
            }
            apiSession.sendMessage(new TextMessage(sendMsg));
        }
        synchronized (this) {
            this.wait(apiTimeout);
        }
        return responseJSON;
    }

    public void onReceiveJson(JSONObject responseJSON) {
        this.responseJSON = responseJSON;
        synchronized (this) {
            this.notify();
        }
    }
}
